import { ref } from 'vue'

import { catchFn } from '@/libs/common'
import { createQuiz, getQuizResult } from '../../api'
import { result } from '../result/data'

/** 会话ID */
let sessionId = ''
/** 测评类型Code */
const typeCode = 'tarot'

/** 当前题目 */
const question = ref<T_TarotCard>()

export { sessionId, typeCode, question }

/**
 * 开始测试
 */
const start = async () => {
  const { data } = await createQuiz(typeCode)

  sessionId = data.sessionId
  question.value = data.tarotCards[0]
}

/**
 * 下一步
 */
const next = () =>
  catchFn(async () => {
    if (question.value) {
      const { data } = await getQuizResult({ sessionId, typeCode })

      result.value = data.tarotResult

      uni.navigateTo({ url: '/pages/quiz/tarot/result/index' })
    } else {
      await start()
    }
  })

/**
 * 清空
 */
const clear = () => (question.value = undefined)

export { start, next, clear }
